/**
 * 
 */
package Bai3;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;
import javax.swing.Timer;

/**
 * @author Nguyen Tuan Luc T127536
 * 
 */
public class cHW05_TrafficPanel03_T127536 extends JPanel {

	int nNumberImg = 5;
	int iCurrentImg = 0;
	// khai bao duong dan cua img
	String[] sImgFileName = { ".\\pics05\\SmallRedCar\\Car-08.gif",
			".\\pics05\\SmallRedCar\\Car-07.gif",
			".\\pics05\\SmallRedCar\\Car-06.gif",
			".\\pics05\\SmallRedCar\\Car-05.gif",
			".\\pics05\\SmallRedCar\\Car-04.gif",

	};
	// khai bao bien de doc image vao bo nho
	BufferedImage[] imgs = new BufferedImage[nNumberImg];
	Timer t;
	int x = -100, y = 370, dx = 5, dy = 10;

	public cHW05_TrafficPanel03_T127536() {

		try {
			// doc hinh anh luu vao bo nho (memory)
			for (int i = 0; i < nNumberImg; i++) {
				imgs[i] = ImageIO.read(new File(sImgFileName[i]));
			}
		} catch (IOException e) {
			// error off reading the file
			System.err.println("loading error");
		}

		t = new Timer(25, new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub

				if (x == 300) {
					iCurrentImg = 1;
					y = y - dy -5;
				}
				if (x == 325) {
					iCurrentImg = 2;
					y = y - dy -10;

				}
				if (x == 335) {
					iCurrentImg = 3;
					y = y - dy - 10;
				}

				if (x == 345) {
					iCurrentImg = 4;
					y = y - dy;
					dx = 0;
				}

				if (y < - getWidth() +500) {
					iCurrentImg = 0;
					x = -100;
					y = 350;
					dx = 5;
				}
				x = x + dx;
				repaint();
			}
		});

	}

	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(Color.BLACK);
		g.fillRect(200, 0, 2, 200);
		g.fillRect(0, 200, 200, 2);
		g.fillRect(500, 0, 2, 200);
		g.fillRect(500, 200, 200, 2);
		g.fillRect(0, 500, 200, 2);
		g.fillRect(500, 500, 200, 2);
		g.fillRect(200, 500, 2, 200);
		g.fillRect(500, 500, 2, 200);

		for (int i = 0; i < 700; i += 80) {
			g.setColor(Color.WHITE);

			g.fillRect(345, 0 + i - 20, 5, 50);

		}
		for (int i = 0; i < 300; i += 80) {
			g.setColor(Color.WHITE);
			g.fillRect(0 + i, 345, 50, 5);
			g.fillRect(400 + i, 345, 50, 5);

		}

		// display image

		g.drawImage(imgs[iCurrentImg], x, y, this);
		// g.drawImage(imgs[1], 10, 50, this);
	}

	public void start() {
		t.start();
	}

	public void stop() {
		t.stop();
	}
}
